﻿using System;
using System.IO;
using System.Net;
using System.Net.Browser;
using System.Xml.Linq;

namespace EarthWatchers.SL.Requests
{
    public class BitLyRequest
    {
        private const string ApiEndpoint = "http://api.bitly.com/v3/shorten";
        private const string Username = "earthwatchers";
        private const string ApiKey = "R_243ddff1052821619fbb781713d7f1d9";
        private string statusCode;
        private string url;

        public delegate void ChangedEventHandler(object sender, EventArgs e);
        public event CommentRequests.ChangedEventHandler BitlyUrlReceived;

        public void ShortenUrl(string longUrl)
        {
            WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);

            var r = new Random();
            var urlrequest = string.Format("{0}?login={1}&apiKey={2}&longUrl={3}&format={4}&r={5}", ApiEndpoint, Username, ApiKey, longUrl, "xml", r.NextDouble());

            var wc = new WebClient();
            wc.OpenReadAsync(new Uri(urlrequest));
            wc.OpenReadCompleted += Received;
        }

        private void Received(object sender, OpenReadCompletedEventArgs e)
        {
            var stream = e.Result;
            var sr = new StreamReader(stream);
            var bitResponse = sr.ReadToEnd();

            var xmlDoc = XDocument.Parse(bitResponse);

            statusCode = xmlDoc.Element("response").Element("status_code").Value;
            if (statusCode.Equals("200"))
                url = xmlDoc.Element("response").Element("data").Element("url").Value;

            OnBitlyUrlReceived(EventArgs.Empty);
        }

        protected virtual void OnBitlyUrlReceived(EventArgs e)
        {
            if (BitlyUrlReceived == null) return;

            BitlyUrlReceived(statusCode.Equals("200") ? url : null, e);
        }
    }
}
